const { ipcRenderer, path, fs, selectedFileName, rootPath, currentThresholds, getMatchingFolderPath } = require('../scripts/common.js');
const { showProcessEditor } = require('./process.js');

// 在文件开头添加全局变量
let skillpointData = null;

// 添加全局变量来存储步骤
window.projectSteps = [];
window.currentStep = 1;

// 添加全局变量来存储执行状态
let executionState = {
    isPaused: false, // 是否暂停
    timer: null,     // 计时器
    stepStartTime: null, // 当前步骤的开始时间
};

// 在文件开头添加格式化时间函数
function formatTime(minutes) {
    const days = Math.floor(minutes / (24 * 60));
    const hours = Math.floor((minutes % (24 * 60)) / 60);
    const mins = Math.floor(minutes % 60);
    
    let result = '';
    if (days > 0) result += `${days}天`;
    if (hours > 0) result += `${hours}时`;
    if (mins > 0 || (days === 0 && hours === 0)) result += `${mins}分`;
    return result;
}

// 添加一个新的格式化函数用于显示分秒
function formatMinutesAndSeconds(minutes) {
    const mins = Math.floor(minutes);
    const secs = Math.round((minutes - mins) * 60);
    
    if (mins === 0) {
        return `${secs}秒`;
    }
    if (secs === 0) {
        return `${mins}分`;
    }
    return `${mins}分${secs}秒`;
}

// 项目相关功能
document.getElementById('projectsLabel').onclick = () => {
    const fileContent = document.getElementById('fileContent');
    
    // 检查第三区域是否为空
    if (fileContent.innerHTML.trim() !== '') {
        // 如果第三区域不为空，清空第三区域、第四区域和下方配方区
        fileContent.innerHTML = '';
        document.querySelector('.card-4').innerHTML = '';
        document.querySelector('.pink-card').innerHTML = '';
    } else {
        // 如果第三区域为空，只清空下方配方区
        document.querySelector('.pink-card').innerHTML = '';
    }

    const fileList = document.getElementById('fileList');
    try {
        const matchingFolderPath = getMatchingFolderPath();
        if (matchingFolderPath) {
            const skillpointPath = path.join(matchingFolderPath, 'skillpoint.json');
            if (fs.existsSync(skillpointPath)) {
                loadProjectsList(skillpointPath);
            } else {
                throw new Error('skillpoint.json not found');
            }
        } else {
            throw new Error('Matching folder not found');
        }
    } catch (error) {
        console.error('Error:', error);
        fileList.innerHTML = '读取文件夹失败：' + error.message;
    }
};

function loadProjectsList(filePath) {
    const fileList = document.getElementById('fileList');
    fileList.innerHTML = '';

    try {
        // 加载并保存 skillpoint 数据
        window.skillpointData = JSON.parse(fs.readFileSync(filePath, 'utf8'));
        skillpointData = window.skillpointData; // 保持本地变量的兼容性
        
        // 添加"+"按钮
        const addButton = document.createElement('div');
        addButton.className = 'file-item add-button';
        addButton.textContent = '+';
        addButton.onclick = () => {
            // 在第三个区域显示项目表单
            const fileContent = document.getElementById('fileContent');
            try {
                const componentHtml = loadComponent('projects');
                if (!componentHtml || componentHtml.includes('失败') || componentHtml.includes('不存在')) {
                    throw new Error('无法加载项目表单');
                }
                
                fileContent.innerHTML = componentHtml;
                
                // 加载skillpoint.json获取能力点和原材料列表
                const abilities = skillpointData.attributes.filter(attr => attr.type === 'ability');
                const materials = skillpointData.attributes.filter(attr => attr.type === 'material');

                // 填充能力点复选框
                const abilitiesContainer = document.getElementById('abilitiesCheckboxes');
                if (abilitiesContainer) {
                    abilities.forEach(ability => {
                        const div = document.createElement('div');
                        div.className = 'checkbox-item';
                        div.innerHTML = `
                            <input type="checkbox" id="ability_${ability.varName}" value="${ability.varName}">
                            <label for="ability_${ability.varName}">${ability.name}</label>
                        `;
                        div.querySelector('input').onchange = updateThresholdEditor;
                        abilitiesContainer.appendChild(div);
                    });
                }

                // 填充原材料复选框
                const materialsContainer = document.getElementById('materialsCheckboxes');
                if (materialsContainer) {
                    materials.forEach(material => {
                        const div = document.createElement('div');
                        div.className = 'checkbox-item';
                        div.innerHTML = `
                            <input type="checkbox" id="material_${material.varName}" value="${material.varName}">
                            <label for="material_${material.varName}">${material.name}</label>
                        `;
                        div.querySelector('input').onchange = updateThresholdEditor;
                        materialsContainer.appendChild(div);
                    });
                }

                // 填充能力点和原材料复选框后，初始化第四区域
                updateThresholdEditor();

                // 只保留项目名称和保存按钮的基本验证
                const projectNameInput = document.getElementById('projectName');
                const saveButton = document.getElementById('saveProject');
                if (projectNameInput && saveButton) {
                    projectNameInput.oninput = () => {
                        saveButton.disabled = projectNameInput.value.trim() === '';
                    };
                    saveButton.setAttribute('data-filepath', filePath);
                }

            } catch (error) {
                console.error('Error showing project form:', error);
                fileContent.innerHTML = '加载项目表单失败: ' + error.message;
            }
        };
        fileList.appendChild(addButton);

        // 读取并显示项目列表
        const projectsPath = path.join(path.dirname(filePath), 'projects');
        if (fs.existsSync(projectsPath)) {
            const projects = fs.readdirSync(projectsPath)
                .filter(file => file.endsWith('.json'))
                .map(file => ({
                    name: file,
                    path: path.join(projectsPath, file)
                }));

            projects.forEach(project => {
                const div = document.createElement('div');
                div.className = 'file-item';
                try {
                    const content = JSON.parse(fs.readFileSync(project.path, 'utf8'));
                    div.textContent = content.name;
                    div.onclick = () => showProjectDetail(project.path);
                    fileList.appendChild(div);
                } catch (error) {
                    console.error('Error reading project file:', error);
                }
            });
        }
    } catch (error) {
        console.error('Error loading projects:', error);
        fileList.innerHTML = '读取项目列表失败';
    }
}

function formatTimestamp() {
    const now = new Date();
    return now.getFullYear() +  // 使用完整年份
           String(now.getMonth() + 1).padStart(2, '0') +  // 月份，补零
           String(now.getDate()).padStart(2, '0') +  // 日期，补零
           String(now.getHours()).padStart(2, '0') +  // 小时，补零
           String(now.getMinutes()).padStart(2, '0');  // 分钟，补零
}

function updateThresholdEditor() {
    if (!skillpointData) {
        console.error('skillpointData is not loaded');
        return;
    }

    // 获取当前选中的能力点和材料
    window.currentAbilities = Array.from(document.querySelectorAll('#abilitiesCheckboxes input:checked')).map(cb => {
        const ability = skillpointData.attributes.find(attr => attr.varName === cb.value);
        return ability || { varName: cb.value, name: cb.nextElementSibling.textContent, step: 1 };
    });

    window.currentMaterials = Array.from(document.querySelectorAll('#materialsCheckboxes input:checked')).map(cb => {
        const material = skillpointData.attributes.find(attr => attr.varName === cb.value);
        return material || { varName: cb.value, name: cb.nextElementSibling.textContent, step: 1 };
    });

    // 显示门槛编辑器
    const container = document.querySelector('.card-4');
    container.innerHTML = `
        <div class="threshold-editor">
            ${window.currentAbilities.length > 0 ? `
                <div class="threshold-section">
                    <h4>设置能力点门槛</h4>
                    ${window.currentAbilities.map(ability => createThresholdInput(ability)).join('')}
                </div>
                <div class="threshold-section">
                    <h4>能力点调整</h4>
                    ${window.currentAbilities.map(ability => createThresholdItem(ability)).join('')}
                </div>
            ` : ''}
            ${window.currentMaterials.length > 0 ? `
                <div class="threshold-section">
                    <h4>设置原材料门槛</h4>
                    ${window.currentMaterials.map(material => createThresholdInput(material)).join('')}
                </div>
            ` : ''}
            <div class="threshold-actions">
                <button id="nextStepBtn" class="next-step-btn">下一步</button>
            </div>
        </div>
    `;

    // 绑定下一步按钮事件
    const nextStepBtn = document.getElementById('nextStepBtn');
    if (nextStepBtn) {
        nextStepBtn.onclick = () => {
            try {
                // 检查项目名称是否已填写
                const projectName = document.getElementById('projectName');
                if (!projectName || !projectName.value.trim()) {
                    alert('请先填写项目名称');
                    projectName?.focus();
                    return;
                }

                if (!window.skillpointData) {
                    throw new Error('项目数据未加载，请重新加载页面');
                }
                // 更新门槛值
                updateThresholds();
                // 显示步骤编辑器
                showProcessEditor(window.currentMaterials);
            } catch (error) {
                console.error('Error handling next step:', error);
                alert('进入下一步失败: ' + error.message);
            }
        };
    }
}

// 原有的设置门槛输入框
function createThresholdInput(item) {
    return `
        <div class="threshold-input" data-varname="${item.varName}" data-name="${item.name}">
            <button class="remove-btn" onclick="window.hideThreshold('${item.type}', '${item.varName}')">×</button>
            <label>${item.name}</label>
            <button class="operator-toggle" 
                    id="operator_${item.varName}" 
                    onclick="window.toggleOperator('${item.varName}')" 
                    data-operator="+">大于</button>
            <input type="number" id="input_threshold_${item.varName}" 
                   value="0" step="${item.step || 1}">
            ${item.unit ? `<span>${item.unit}</span>` : ''}
        </div>
    `;
}

// 新增的能力点调整列表
function createThresholdItem(item) {
    return `
        <div class="threshold-item" data-varname="${item.varName}" data-name="${item.name}">
            <button class="remove-btn" onclick="window.hideThreshold('change', '${item.varName}')">×</button>
            <span>${item.name}</span>
            <button class="step-btn" onclick="window.adjustThreshold('${item.varName}', -${item.step || 1})">←</button>
            <span id="adjust_threshold_${item.varName}">0</span>
            <button class="step-btn" onclick="window.adjustThreshold('${item.varName}', ${item.step || 1})">→</button>
        </div>
    `;
}

// 修改 adjustThreshold 函数，添加精度处理
function adjustThreshold(varName, step) {
    const thresholdElement = document.getElementById(`adjust_threshold_${varName}`);
    if (thresholdElement) {
        let currentValue = parseFloat(thresholdElement.textContent) || 0;
        step = parseFloat(step);
        // 根据step的小数位数来确定精度
        const precision = step.toString().split('.')[1]?.length || 0;
        currentValue = parseFloat((currentValue + step).toFixed(precision));
        thresholdElement.textContent = currentValue;
    }
}

// 将函数添加到 window 对象上，使其在 onclick 中可用
window.adjustThreshold = adjustThreshold;

window.toggleOperator = function(varName) {
    const button = document.getElementById(`operator_${varName}`);
    const currentOperator = button.dataset.operator;
    
    if (currentOperator === '+') {
        button.dataset.operator = '-';
        button.textContent = '小于';
    } else {
        button.dataset.operator = '+';
        button.textContent = '大于';
    }
}

function updateThresholds() {
    currentThresholds.abilities = window.currentAbilities.map(ability => {
        const inputElement = document.getElementById(`input_threshold_${ability.varName}`);
        const operatorElement = document.getElementById(`operator_${ability.varName}`);
        if (!inputElement || !operatorElement) return null;
        
        return {
            varName: ability.varName,
            name: ability.name,
            threshold: inputElement.value,
            operator: operatorElement.dataset.operator
        };
    }).filter(item => item !== null && item.threshold !== '');

    currentThresholds.materials = window.currentMaterials.map(material => {
        const inputElement = document.getElementById(`input_threshold_${material.varName}`);
        const operatorElement = document.getElementById(`operator_${material.varName}`);
        if (!inputElement || !operatorElement) return null;

        return {
            varName: material.varName,
            name: material.name,
            threshold: inputElement.value,
            operator: operatorElement.dataset.operator
        };
    }).filter(item => item !== null && item.threshold !== '');

    // 添加能力点变化
    currentThresholds.abilityChanges = window.currentAbilities.map(ability => {
        const element = document.getElementById(`adjust_threshold_${ability.varName}`);
        if (!element) return null;
        
        const value = element.textContent;
        if (value && value !== '0') {
            return {
                varName: ability.varName,
                name: ability.name,
                change: value
            };
        }
        return null;
    }).filter(item => item !== null);
}

function showProjectDetail(projectPath) {
    const fileContent = document.getElementById('fileContent');
    try {
        projectPath = projectPath.replace(/\\/g, path.sep);
        
        const content = JSON.parse(fs.readFileSync(projectPath, 'utf8'));
        const skillpointPath = path.join(path.dirname(path.dirname(projectPath)), 'skillpoint.json');
        const skillpointData = JSON.parse(fs.readFileSync(skillpointPath, 'utf8'));
        
        // 计算材料总消耗和总产出
        const materialConsumption = {};
        const materialProduction = {};
        const methodsUsed = new Set();
        
        content.steps.forEach(step => {
            // 统计消耗材料
            step.materials?.forEach(material => {
                materialConsumption[material.name] = (materialConsumption[material.name] || 0) + 
                    parseInt(material.amount || 0);
            });
            
            // 统计产出材料
            step.products?.forEach(product => {
                materialProduction[product.name] = (materialProduction[product.name] || 0) + 
                    parseInt(product.amount || 0);
            });
            
            // 收集使用的方法
            step.methods?.forEach(method => {
                methodsUsed.add(method.name);
            });
        });

        let html = `<div class="project-detail">`;
        
        // 添加基本信息显示
        html += `<h2>${content.name}</h2>`;

        // 计算平均执行时间
        if (content.executions && content.executions.length > 0) {
            const totalMinutes = content.executions.reduce((sum, exec) => 
                sum + exec.totalActualTime, 0);
            const executionCount = content.executions.length;
            const avgMinutes = Math.floor(totalMinutes / executionCount);
            const avgSeconds = Math.round((totalMinutes / executionCount - avgMinutes) * 60);
            
            let avgTimeDisplay = '';
            if (avgMinutes === 0) {
                avgTimeDisplay = `${avgSeconds}秒`;
            } else if (avgSeconds === 0) {
                avgTimeDisplay = `${avgMinutes}分`;
            } else {
                avgTimeDisplay = `${avgMinutes}分${avgSeconds}秒`;
            }
            
            html += `
                <div class="execution-stats">
                    <div class="stats-header">平均用时(${executionCount}次)：</div>
                    <div class="stats-value">${avgTimeDisplay}</div>
                </div>`;
        }

        // 项目详情（如果有）
        if (content.detail) {
            html += `<div class="detail-section">
                <h3>项目详情</h3>
                <p>${content.detail}</p>
            </div>`;
        }

        // 步骤列表
        html += `<div class="detail-section">
            <h3>执行步骤</h3>
            <div class="steps-list">`;
        
        content.steps.forEach((step, index) => {
            // 计算这个步骤的平均用时
            let avgStepTime = '';
            if (content.executions && content.executions.length > 0) {
                const totalStepMinutes = content.executions.reduce((sum, exec) => 
                    sum + (exec.actualTimes[index] || 0), 0);
                const avgStepMinutes = Math.floor(totalStepMinutes / content.executions.length);
                const avgStepSeconds = Math.round((totalStepMinutes / content.executions.length - avgStepMinutes) * 60);
                
                if (avgStepMinutes === 0) {
                    avgStepTime = `建议用时：${avgStepSeconds}秒`;
                } else if (avgStepSeconds === 0) {
                    avgStepTime = `建议用时：${avgStepMinutes}分`;
                } else {
                    avgStepTime = `建议用时：${avgStepMinutes}分${avgStepSeconds}秒`;
                }
            }

            html += `
                <div class="step-detail">
                    <div class="step-content">
                        ${index + 1}. ${step.description}
                        ${avgStepTime ? `<div class="step-time">${avgStepTime}</div>` : ''}
                    </div>
                </div>`;
        });
        
        html += `</div></div>`;

        // 好处
        if (content.benefits) {
            html += `
                <div class="detail-section">
                    <h3>完成项目的好处</h3>
                    <p>${content.benefits}</p>
                </div>
            `;
        }

        // 风险
        if (content.risks) {
            html += `
                <div class="detail-section">
                    <h3>不完成项目的危害</h3>
                    <p>${content.risks}</p>
                </div>
            `;
        }

        // 材料消耗
        if (Object.keys(materialConsumption).length > 0) {
            html += `
                <div class="detail-section">
                    <h3>材料消耗</h3>
                    <div class="materials-list">
                        ${Object.entries(materialConsumption).map(([name, amount]) => {
                            const step = content.steps.find(s => 
                                s.materials?.find(m => m.name === name))?.materials.find(m => 
                                m.name === name);
                            // 使用原始字符串值来避免精度问题
                            const displayAmount = parseFloat(step?.amount || amount).toFixed(
                                String(step?.amount || amount).split('.')[1]?.length || 0
                            );
                            return `<div class="material-item">
                                ${name}: ${displayAmount}${step?.unit || ''}
                            </div>`;
                        }).join('')}
                    </div>
                </div>
            `;
        }

        // 使用方法
        if (methodsUsed.size > 0) {
            html += `
                <div class="detail-section">
                    <h3>使用方法</h3>
                    <div class="methods-list">
                        ${Array.from(methodsUsed).map(method =>
                            `<div class="method-item">${method}</div>`
                        ).join('')}
                    </div>
                </div>
            `;
        }

        // 材料产出
        if (Object.keys(materialProduction).length > 0) {
            html += `
                <div class="detail-section">
                    <h3>材料产出</h3>
                    <div class="materials-list">
                        ${Object.entries(materialProduction).map(([name, amount]) => {
                            const step = content.steps.find(s => 
                                s.products?.find(p => p.name === name))?.products.find(p => 
                                p.name === name);
                            // 使用原始字符串值来避免精度问题
                            const displayAmount = parseFloat(step?.amount || amount).toFixed(
                                String(step?.amount || amount).split('.')[1]?.length || 0
                            );
                            return `<div class="material-item">
                                ${name}: ${displayAmount}${step?.unit || ''}
                            </div>`;
                        }).join('')}
                    </div>
                </div>
            `;
        }

        // 门槛值
        if (content.thresholds) {
            html += `
                <div class="detail-section">
                    <h3>门槛值</h3>
                    <div class="thresholds-list">
                        ${(content.thresholds.abilities || []).map(ability => {
                            const displayValue = parseFloat(ability.threshold).toFixed(
                                String(ability.threshold).split('.')[1]?.length || 0
                            );
                            const abilityData = skillpointData.attributes.find(attr => attr.varName === ability.varName);
                            return `<div class="threshold-item">
                                ${ability.name}：${displayValue}${abilityData?.unit || ''}${ability.operator === '+' ? '以上' : '以下'}
                            </div>`;
                        }).join('')}
                        ${(content.thresholds.materials || []).map(material => {
                            const displayValue = parseFloat(material.threshold).toFixed(
                                String(material.threshold).split('.')[1]?.length || 0
                            );
                            const materialData = skillpointData.attributes.find(attr => attr.varName === material.varName);
                            return `<div class="threshold-item">
                                ${material.name}：${displayValue}${materialData?.unit || ''}${material.operator === '+' ? '以上' : '以下'}
                            </div>`;
                        }).join('')}
                    </div>
                </div>
            `;
        }

        // 添加能力点变化部分
        if (content.thresholds?.abilityChanges?.length > 0) {
            html += `
                <div class="detail-section">
                    <h3>能力点变化</h3>
                    <div class="ability-changes-list">
                        ${content.thresholds.abilityChanges.map(ability => 
                            `<div class="ability-change-item">
                                ${ability.name}: ${ability.change > 0 ? '+' : ''}${ability.change}
                            </div>`
                        ).join('')}
                    </div>
                </div>
            `;
        }

        // 检查门槛是否满足并添加执行按钮
        const thresholdsMet = checkThresholds(content.thresholds, skillpointData.attributes);
        if (thresholdsMet) {
            html += `<button class="execute-btn" onclick='startProjectExecution(${JSON.stringify(projectPath)})'>执行</button>`;
        } else {
            html += `<div class="threshold-warning">门槛值不满足，无法执行</div>`;
        }
        
        fileContent.innerHTML = html;
    } catch (error) {
        console.error('Error showing project detail:', error);
        fileContent.innerHTML = '加载项目详情失败: ' + error.message;
    }
}

function checkThresholds(thresholds, attributes) {
    if (!thresholds || !attributes) return false;
    
    // 检查能力点门槛
    for (const ability of thresholds.abilities || []) {
        const attr = attributes.find(a => a.varName === ability.varName);
        if (!attr || (attr.currentValue || attr.defaultValue || 0) < ability.value) {
            return false;
        }
    }
    
    // 检查材料门槛
    for (const material of thresholds.materials || []) {
        const attr = attributes.find(a => a.varName === material.varName);
        if (!attr || (attr.currentValue || attr.defaultValue || 0) < material.value) {
            return false;
        }
    }
    
    return true;
}

// 修改 updateRecipe 函数
window.updateRecipe = function(materials) {
    const recipeContainer = document.querySelector('.pink-card');
    const consumedMaterials = Array.from(document.querySelectorAll('input[id^="process_"]:checked'))
        .map(input => ({
            varName: input.value,
            name: input.dataset.name,
            amount: parseFloat(input.dataset.amount || input.dataset.step),
            step: parseFloat(input.dataset.step),
            unit: input.dataset.unit
        }));

    const usedMethods = Array.from(document.querySelectorAll('input[id^="method_"]:checked'))
        .map(input => ({
            varName: input.value,
            name: input.dataset.name
        }));

    const producedMaterials = Array.from(document.querySelectorAll('input[id^="product_"]:checked'))
        .map(input => ({
            varName: input.value,
            name: input.dataset.name,
            amount: parseFloat(input.dataset.amount || input.dataset.step),
            step: parseFloat(input.dataset.step),
            unit: input.dataset.unit
        }));

    recipeContainer.innerHTML = `
        <div class="recipe-container">
            <div class="recipe-left">
                <div class="section-title">消耗材料</div>
                <div class="consumed-materials">
                    ${consumedMaterials.map(material => `
                        <div class="recipe-item" data-varname="${material.varName}">
                            <span class="recipe-name">${material.name}</span>
                            <div class="recipe-amount-wrapper">
                                <button class="amount-btn plus" onclick="adjustAmount('${material.varName}', 1, ${material.step}, true)">+</button>
                                <span class="recipe-amount">${material.amount.toFixed(material.step.toString().split('.')[1]?.length || 0)}${material.unit}</span>
                                <button class="amount-btn minus" onclick="adjustAmount('${material.varName}', -1, ${material.step}, true)">-</button>
                            </div>
                        </div>
                    `).join('')}
                </div>
                <div class="section-title">使用方法</div>
                <div class="recipe-methods">
                    ${usedMethods.map(method => `
                        <div class="recipe-item" data-varname="${method.varName}">
                            <span class="recipe-name">${method.name}</span>
                            <button class="remove-btn" onclick="removeMethod('${method.varName}')">×</button>
                        </div>
                    `).join('')}
                </div>
            </div>
            <div class="recipe-right">
                <div class="section-title">产出材料</div>
                <div class="produced-materials">
                    ${producedMaterials.map(material => `
                        <div class="recipe-item" data-varname="${material.varName}">
                            <span class="recipe-name">${material.name}</span>
                            <div class="recipe-amount-wrapper">
                                <button class="amount-btn plus" onclick="adjustAmount('${material.varName}', 1, ${material.step}, false)">+</button>
                                <span class="recipe-amount">${material.amount.toFixed(material.step.toString().split('.')[1]?.length || 0)}${material.unit}</span>
                                <button class="amount-btn minus" onclick="adjustAmount('${material.varName}', -1, ${material.step}, false)">-</button>
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        </div>
    `;

    // 更新步骤描述
    updateStepDescription(consumedMaterials, usedMethods, producedMaterials);
};

// 修改 adjustAmount 函数
window.adjustAmount = function(varName, direction, step, isConsumed) {
    const checkbox = document.getElementById(`${isConsumed ? 'process' : 'product'}_${varName}`);
    if (!checkbox) return;

    const currentAmount = parseFloat(checkbox.dataset.amount || checkbox.dataset.step);
    const newAmount = currentAmount + (direction * parseFloat(step));

    if (newAmount <= 0) {
        // 数量为0时取消勾选并更新配方
        checkbox.checked = false;
        updateRecipe(window.currentMaterials);
    } else {
        // 更新数量并重新显示配方
        checkbox.dataset.amount = newAmount;
        updateRecipe(window.currentMaterials);
    }
};

// 添加移除方法的函数
window.removeMethod = function(varName) {
    const checkbox = document.getElementById(`method_${varName}`);
    if (checkbox) {
        checkbox.checked = false;
        updateRecipe(window.currentMaterials);
    }
};

function updateStepDescription(consumed, methods, produced) {
    const description = document.getElementById('stepDescription');
    if (!description) return;

    const consumedText = consumed.map(m => `${m.amount.toFixed(m.step.toString().split('.')[1]?.length || 0)}${m.unit}${m.name}`).join('、');
    const methodsText = methods.map(m => m.name).join('、');
    const producedText = produced.map(m => `${m.amount.toFixed(m.step.toString().split('.')[1]?.length || 0)}${m.unit}${m.name}`).join('、');

    let text = '';
    if (consumedText) text += `使用${consumedText}`;
    if (methodsText) text += `，通过${methodsText}`;
    if (producedText) text += `，生产出${producedText}`;

    description.value = text || '';
}

// 添加保存步骤的函数
window.saveStep = function() {
    try {
        // 获取当前步骤的数据
        const consumedMaterials = Array.from(document.querySelectorAll('input[id^="process_"]:checked'))
            .map(input => ({
                varName: input.value,
                name: input.dataset.name,
                amount: input.dataset.step,
                unit: input.dataset.unit
            }));

        const usedMethods = Array.from(document.querySelectorAll('input[id^="method_"]:checked'))
            .map(input => ({
                varName: input.value,
                name: input.dataset.name
            }));

        const producedMaterials = Array.from(document.querySelectorAll('input[id^="product_"]:checked'))
            .map(input => ({
                varName: input.value,
                name: input.dataset.name,
                amount: input.dataset.step,
                unit: input.dataset.unit
            }));

        const description = document.getElementById('stepDescription').value;

        // 保存当前步骤
        const step = {
            stepNumber: window.currentStep,
            materials: consumedMaterials,
            methods: usedMethods,
            products: producedMaterials,
            description: description
        };

        // 更新或添加步骤
        const existingStepIndex = window.projectSteps.findIndex(s => s.stepNumber === window.currentStep);
        if (existingStepIndex >= 0) {
            window.projectSteps[existingStepIndex] = step;
        } else {
            window.projectSteps.push(step);
        }

        // 进入下一步
        window.currentStep++;
        showNextStep();
    } catch (error) {
        console.error('Error saving step:', error);
        alert('保存步骤失败: ' + error.message);
    }
};

// 显示下一步的函数
function showNextStep() {
    const fileContent = document.getElementById('fileContent');
    fileContent.innerHTML = `
        <div class="process-editor">
            <h3>第${window.currentStep}步</h3>
            <div class="process-section">
                <h4>消耗材料</h4>
                <div class="materials-list">
                    ${window.currentMaterials.map(material => `
                        <div class="checkbox-item">
                            <input type="checkbox" id="process_${material.varName}" value="${material.varName}"
                                   data-name="${material.name}" data-step="${material.step || 1}"
                                   data-unit="${material.unit || ''}"
                                   onchange="updateRecipe(window.currentMaterials)">
                            <label for="process_${material.varName}">${material.name}</label>
                        </div>
                    `).join('')}
                </div>
            </div>
            <div class="process-section">
                <h4>使用方法</h4>
                <div class="methods-list">
                    ${skillpointData.attributes.filter(attr => attr.type === 'method').map(method => `
                        <div class="checkbox-item">
                            <input type="checkbox" id="method_${method.varName}" value="${method.varName}"
                                   data-name="${method.name}"
                                   onchange="updateRecipe(window.currentMaterials)">
                            <label for="method_${method.varName}">${method.name}</label>
                        </div>
                    `).join('')}
                </div>
            </div>
            <div class="process-section">
                <h4>产出材料</h4>
                <div class="products-list">
                    ${window.currentMaterials.map(material => `
                        <div class="checkbox-item">
                            <input type="checkbox" id="product_${material.varName}" value="${material.varName}"
                                   data-name="${material.name}" data-step="${material.step || 1}"
                                   data-unit="${material.unit || ''}"
                                   onchange="updateRecipe(window.currentMaterials)">
                            <label for="product_${material.varName}">${material.name}</label>
                        </div>
                    `).join('')}
                </div>
            </div>
            <div class="process-section">
                <h4>步骤描述</h4>
                <textarea id="stepDescription" placeholder="请描述这一步骤的具体操作..."></textarea>
            </div>
            <div class="process-actions">
                <button class="prev-btn" onclick="handlePrevStep()">返回</button>
                ${window.currentStep >= 2 ? 
                    `<button class="complete-btn" onclick="saveProject()">完成</button>` :
                    `<button class="next-btn" onclick="handleNextStep()">下一步</button>`
                }
            </div>
        </div>
    `;

    // 清空配方显示
    document.querySelector('.pink-card').innerHTML = '';

    // 更新配方显示（如果需要的话）
    updateRecipe(window.currentMaterials);
}

// 显示上一步的函数
window.showPreviousStep = function() {
    if (window.currentStep > 1) {
        window.currentStep--;
        showNextStep();
        // 恢复上一步的选择状态
        const previousStep = window.projectSteps.find(s => s.stepNumber === window.currentStep);
        if (previousStep) {
            // 恢复消耗材料的选择
            previousStep.materials.forEach(material => {
                const checkbox = document.getElementById(`process_${material.varName}`);
                if (checkbox) checkbox.checked = true;
            });

            // 恢复使用方法的选择
            previousStep.methods.forEach(method => {
                const checkbox = document.getElementById(`method_${method.varName}`);
                if (checkbox) checkbox.checked = true;
            });

            // 恢复产出材料的选择
            previousStep.products.forEach(product => {
                const checkbox = document.getElementById(`product_${product.varName}`);
                if (checkbox) checkbox.checked = true;
            });

            // 恢复步骤描述
            const description = document.getElementById('stepDescription');
            if (description) description.value = previousStep.description;

            // 更新配方显示
            updateRecipe(window.currentMaterials);
        }
    } else {
        // 如果是第一步，则返回到项目标签，只更新相关区域
        const fileList = document.getElementById('fileList');
        loadProjectsList(window.currentProjectPath);
    }
};

// 修改第一步和后续步骤的按钮
function showStepEditor(stepNumber) {
    const stepEditor = document.querySelector('.card-4');
    stepEditor.innerHTML = `
        <div class="process-editor">
            <h3>第${stepNumber}步</h3>
            <div class="process-section">
                <h4>消耗材料</h4>
                <div class="materials-list">
                    ${window.currentMaterials.map(material => `
                        <div class="checkbox-item">
                            <input type="checkbox" id="process_${material.varName}" value="${material.varName}"
                                   data-name="${material.name}" data-step="${material.step || 1}"
                                   data-unit="${material.unit || ''}"
                                   onchange="updateRecipe(window.currentMaterials)">
                            <label for="process_${material.varName}">${material.name}</label>
                        </div>
                    `).join('')}
                </div>
            </div>
            <div class="process-section">
                <h4>使用方法</h4>
                <div class="methods-list">
                    ${skillpointData.attributes.filter(attr => attr.type === 'method').map(method => `
                        <div class="checkbox-item">
                            <input type="checkbox" id="method_${method.varName}" value="${method.varName}"
                                   data-name="${method.name}"
                                   onchange="updateRecipe(window.currentMaterials)">
                            <label for="method_${method.varName}">${method.name}</label>
                        </div>
                    `).join('')}
                </div>
            </div>
            <div class="process-section">
                <h4>产出材料</h4>
                <div class="products-list">
                    ${window.currentMaterials.map(material => `
                        <div class="checkbox-item">
                            <input type="checkbox" id="product_${material.varName}" value="${material.varName}"
                                   data-name="${material.name}" data-step="${material.step || 1}"
                                   data-unit="${material.unit || ''}"
                                   onchange="updateRecipe(window.currentMaterials)">
                            <label for="product_${material.varName}">${material.name}</label>
                        </div>
                    `).join('')}
                </div>
            </div>
            <div class="process-section">
                <h4>步骤描述</h4>
                <textarea id="stepDescription" placeholder="请描述这一步骤的具体操作..."></textarea>
            </div>
            <div class="process-actions">
                <button class="prev-btn" onclick="handlePrevStep()">返回</button>
                <button class="next-btn" onclick="handleNextStep()">下一步</button>
                <button class="complete-btn" onclick="saveProject()">完成</button>
            </div>
        </div>
    `;

    // 绑定复选框变化事件
    document.querySelectorAll('.process-editor input[type="checkbox"]').forEach(checkbox => {
        checkbox.onchange = () => updateRecipe(window.currentMaterials);
    });

    // 显示初始配方
    updateRecipe(window.currentMaterials);
}

// 处理返回按钮
window.handlePrevStep = function() {
    if (window.currentStep > 1) {
        window.currentStep--;
        showStepEditor(window.currentStep);
        // 恢复上一步的状态
        const previousStep = window.projectSteps.find(s => s.stepNumber === window.currentStep);
        if (previousStep) {
            restoreStepState(previousStep);
        }
    } else {
        // 返回到门槛值设置，只更新第三区域
        updateThresholdEditor();
    }
};

// 处理下一步按钮
window.handleNextStep = function() {
    // 保存当前步骤
    saveCurrentStep();
    // 进入下一步
    window.currentStep++;
    showStepEditor(window.currentStep);
};

// 保存当前步骤
function saveCurrentStep() {
    const step = {
        stepNumber: window.currentStep,
        materials: Array.from(document.querySelectorAll('input[id^="process_"]:checked'))
            .map(input => ({
                varName: input.value,
                name: input.dataset.name,
                amount: input.dataset.step,
                unit: input.dataset.unit
            })),
        methods: Array.from(document.querySelectorAll('input[id^="method_"]:checked'))
            .map(input => ({
                varName: input.value,
                name: input.dataset.name
            })),
        products: Array.from(document.querySelectorAll('input[id^="product_"]:checked'))
            .map(input => ({
                varName: input.value,
                name: input.dataset.name,
                amount: input.dataset.step,
                unit: input.dataset.unit
            })),
        description: document.getElementById('stepDescription').value
    };

    const existingStepIndex = window.projectSteps.findIndex(s => s.stepNumber === window.currentStep);
    if (existingStepIndex >= 0) {
        window.projectSteps[existingStepIndex] = step;
    } else {
        window.projectSteps.push(step);
    }
}

// 保存整个项目
window.saveProject = async function() {
    try {
        // 保存最后一步
        saveCurrentStep();

        // 获取项目基本信息
        const projectName = document.getElementById('projectName').value;
        if (!projectName) {
            throw new Error('项目名称不能为空');
        }

        const projectDetail = document.getElementById('projectDetail').value;
        const projectBenefits = document.getElementById('projectBenefits').value;
        const projectRisks = document.getElementById('projectRisks').value;

        // 构建项目数据
        const projectData = {
            name: projectName,
            detail: projectDetail,
            benefits: projectBenefits,
            risks: projectRisks,
            thresholds: currentThresholds,
            steps: window.projectSteps
        };

        // 生成文件名
        const timestamp = formatTimestamp();
        const fileName = `${timestamp}_${projectName}.json`;

        // 获取projects文件夹路径
        const matchingFolderPath = getMatchingFolderPath();
        if (!matchingFolderPath) {
            throw new Error('无法获取保存路径');
        }

        const projectsPath = path.join(matchingFolderPath, 'projects');
        if (!fs.existsSync(projectsPath)) {
            fs.mkdirSync(projectsPath);
        }

        // 保存文件
        const filePath = path.join(projectsPath, fileName);
        await saveProject(filePath, projectData);

        // 返回到项目列表
        document.getElementById('projectsLabel').click();
    } catch (error) {
        console.error('Error saving project:', error);
        alert('保存项目失败: ' + error.message);
    }
};

window.startProjectExecution = function(projectPath) {
    try {
        // 确保路径格式正确
        projectPath = projectPath.replace(/\\/g, path.sep);
        
        // 检查文件是否存在
        if (!fs.existsSync(projectPath)) {
            throw new Error(`找不到项目文件: ${projectPath}`);
        }

        const content = JSON.parse(fs.readFileSync(projectPath, 'utf8'));
        window.currentProject = {
            path: projectPath,
            data: content,
            currentStep: 0,
            estimatedTimes: [],
            actualTimes: []
        };
        
        // 清空下方配方区
        document.querySelector('.pink-card').innerHTML = '';
        
        // 在第三区域显示时间估计界面
        const fileContent = document.querySelector('.file-content');
        if (!fileContent) {
            throw new Error('找不到显示区域');
        }
        showTimeEstimation(fileContent);
    } catch (error) {
        console.error('Error starting project execution:', error);
        document.querySelector('.file-content').innerHTML = '启动项目执行失败: ' + error.message;
    }
}

function showTimeEstimation(fileContent) {
    const step = window.currentProject.data.steps[window.currentProject.currentStep];
    
    // 计算这个步骤的平均用时
    let avgStepTime = '';
    if (window.currentProject.data.executions && window.currentProject.data.executions.length > 0) {
        const totalStepMinutes = window.currentProject.data.executions.reduce((sum, exec) => 
            sum + (exec.actualTimes[window.currentProject.currentStep] || 0), 0);
        avgStepTime = formatMinutesAndSeconds(totalStepMinutes / window.currentProject.data.executions.length);
    }

    fileContent.innerHTML = `
        <div class="time-estimation">
            <h3>预估时间</h3>
            <div class="step-content">
                ${window.currentProject.currentStep + 1}. ${step.description}
                ${avgStepTime ? `<div class="step-time">建议用时：${avgStepTime}</div>` : ''}
            </div>
            <div class="time-inputs">
                <div class="time-input">
                    <button onclick="window.adjustTime('left', 'days')">←</button>
                    <div class="time-value">
                        <label>天</label>
                        <input type="number" id="days" min="0" value="0">
                    </div>
                    <button onclick="window.adjustTime('right', 'days')">→</button>
                </div>
                <div class="time-input">
                    <button onclick="window.adjustTime('left', 'hours')">←</button>
                    <div class="time-value">
                        <label>时</label>
                        <input type="number" id="hours" min="0" max="23" value="0">
                    </div>
                    <button onclick="window.adjustTime('right', 'hours')">→</button>
                </div>
                <div class="time-input">
                    <button onclick="window.adjustTime('left', 'minutes')">←</button>
                    <div class="time-value">
                        <label>分</label>
                        <input type="number" id="minutes" min="0" max="59" value="0">
                    </div>
                    <button onclick="window.adjustTime('right', 'minutes')">→</button>
                </div>
            </div>
            <button class="next-btn" onclick="window.saveTimeEstimation()">
                ${window.currentProject.currentStep === window.currentProject.data.steps.length - 1 ? '开始执行' : '下一步'}
            </button>
        </div>
    `;
}

// 修改时间调整函数
window.adjustTime = function(direction, field) {
    const input = document.getElementById(field);
    const value = parseInt(input.value) || 0;
    const min = parseInt(input.min) || 0;
    const max = parseInt(input.max) || Infinity;
    
    if (direction === 'left') {
        input.value = Math.max(min, value - 1);
    } else {
        input.value = Math.min(max, value + 1);
    }
}

window.saveTimeEstimation = function() {
    const days = parseInt(document.getElementById('days').value) || 0;
    const hours = parseInt(document.getElementById('hours').value) || 0;
    const minutes = parseInt(document.getElementById('minutes').value) || 0;
    
    const totalMinutes = days * 24 * 60 + hours * 60 + minutes;
    window.currentProject.estimatedTimes[window.currentProject.currentStep] = totalMinutes;
    
    const fileContent = document.querySelector('.file-content');  // 获取正确的元素
    if (window.currentProject.currentStep === window.currentProject.data.steps.length - 1) {
        startExecution(fileContent);
    } else {
        window.currentProject.currentStep++;
        showTimeEstimation(fileContent);
    }
}

// 启动执行
function startExecution(fileContent) {
    try {
        // 强制重置 currentStep 为 0
        window.currentProject.currentStep = 0;
        renderExecutionView(fileContent);
    } catch (error) {
        console.error('Error starting execution:', error);
        fileContent.innerHTML = '启动执行失败: ' + error.message;
    }
}

// 继续执行
function continueExecution(fileContent) {
    try {
        renderExecutionView(fileContent);
    } catch (error) {
        console.error('Error continuing execution:', error);
        fileContent.innerHTML = '继续执行失败: ' + error.message;
    }
}

// 渲染执行视图
function renderExecutionView(fileContent) {
    const maxTime = Math.max(...window.currentProject.estimatedTimes);
    
    fileContent.innerHTML = `
        <div class="execution-view">
            <h3>项目执行</h3>
            <div class="progress-list">
                ${window.currentProject.data.steps.map((step, index) => `
                    <div class="progress-item">
                        <div class="progress-label">
                            <span>步骤 ${index + 1}</span>
                            <span class="time-info">
                                预计：${formatTime(window.currentProject.estimatedTimes[index])}
                                <span id="actual-time-${index}">实际：0分钟</span>
                            </span>
                        </div>
                        <div class="progress-track" style="width: ${(window.currentProject.estimatedTimes[index] / maxTime) * 100}%">
                            <div class="progress-bar ${index === window.currentProject.currentStep ? 'current' : ''}" 
                                 id="progress-${index}">
                            </div>
                            <div class="progress-bar-overflow" id="progress-overflow-${index}"></div>
                        </div>
                    </div>
                `).join('')}
            </div>
            <div class="execution-controls">
                <div class="control-row">
                    <button class="control1-btn cancel-btn" onclick="window.confirmCancel()">取消</button>
                    <button class="control1-btn complete-btn" onclick="window.completeProject()">完成此步</button>
                </div>
            </div>
            <div class="execution-controls">
                <div class="control-row">
                    <button class="control2-btn pause-btn" id="pauseBtn" onclick="window.togglePause()">暂停</button>
                    <button class="control2-btn thought-btn" onclick="window.showThoughtForm()">记录心得</button>
                </div>
            </div>
        </div>
    `;
    
    // 重置计时器状态
    executionState.isPaused = false;
    if (executionState.timer) {
        clearInterval(executionState.timer);
    }
    startStepTimer(); // 启动当前步骤的计时器
}

// 启动步骤计时器
function startStepTimer() {
    executionState.stepStartTime = Date.now();
    executionState.timer = setInterval(updateProgress, 1000);
}

// 更新进度
function updateProgress() {
    if (executionState.isPaused) return;
    
    const elapsed = (Date.now() - executionState.stepStartTime) / 1000 / 60; // 转换为分钟
    const estimatedTime = window.currentProject.estimatedTimes[window.currentProject.currentStep];
    const progress = (elapsed / estimatedTime) * 100;
    
    const progressBar = document.getElementById(`progress-${window.currentProject.currentStep}`);
    const progressOverflow = document.getElementById(`progress-overflow-${window.currentProject.currentStep}`);
    const actualTimeDisplay = document.getElementById(`actual-time-${window.currentProject.currentStep}`);
    
    if (progressBar && progressOverflow) {
        if (progress <= 100) {
            progressBar.style.width = `${progress}%`;
            progressOverflow.style.width = '0';
        } else {
            progressBar.style.width = '100%';
            progressOverflow.style.width = `${progress - 100}%`;
        }
    }
    
    if (actualTimeDisplay) {
        actualTimeDisplay.textContent = `实际：${formatTime(elapsed)}`;
    }
}

// 切换暂停/继续
window.togglePause = function() {
    executionState.isPaused = !executionState.isPaused;
    document.getElementById('pauseBtn').textContent = executionState.isPaused ? '继续' : '暂停';
}

// 修改完成当前步骤的函数
window.completeProject = async function() {
    try {
        // 停止计时器
        if (executionState.timer) {
            clearInterval(executionState.timer);
        }

        // 保存当前步骤的心得（如果有的话）
        if (document.querySelector('.thought-form')) {
            await window.saveThought();
        }

        // 计算当前步骤的实际用时
        const elapsed = (Date.now() - executionState.stepStartTime) / 1000 / 60; // 转换为分钟
        window.currentProject.actualTimes[window.currentProject.currentStep] = elapsed;

        // 检查是否是最后一步
        if (window.currentProject.currentStep === window.currentProject.data.steps.length - 1) {
            // 如果是最后一步，添加本次执行记录
            const executionRecord = {
                timestamp: formatTimestamp(),
                estimatedTimes: window.currentProject.estimatedTimes,
                actualTimes: window.currentProject.actualTimes,
                totalEstimatedTime: window.currentProject.estimatedTimes.reduce((sum, time) => sum + time, 0),
                totalActualTime: window.currentProject.actualTimes.reduce((sum, time) => sum + time, 0)
            };

            // 初始化或更新执行记录数组
            if (!window.currentProject.data.executions) {
                window.currentProject.data.executions = [];
            }
            window.currentProject.data.executions.push(executionRecord);

            // 更新项目状态和能力点
            await saveProject(window.currentProject.path, window.currentProject.data);
            // 返回到项目详情页面
            showProjectDetail(window.currentProject.path);
        } else {
            // 如果不是最后一步，进入下一步
            window.currentProject.currentStep++;
            const fileContent = document.querySelector('.file-content');
            renderExecutionView(fileContent);
        }
    } catch (error) {
        console.error('Error completing step:', error);
        alert('完成步骤时出错: ' + error.message);
    }
};

// 添加显示心得表单的函数
window.showThoughtForm = function() {
    const card4 = document.querySelector('.card-4');
    const now = new Date();
    const timestamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}`;
    
    card4.innerHTML = `
        <div class="thought-form">
            <div class="form-group">
                <label>时间戳</label>
                <input type="text" id="thoughtTimestamp" value="${timestamp}" readonly>
            </div>
            <div class="form-group">
                <label>遇到的问题</label>
                <textarea id="thoughtProblem" rows="4" placeholder="描述遇到的问题..."></textarea>
            </div>
            <div class="form-group status-group">
                <label>状态</label>
                <div class="radio-group">
                    <label>
                        <input type="radio" name="status" value="unsolved" onclick="window.toggleThoughtStatus('unsolved')">
                        未解决
                    </label>
                    <label>
                        <input type="radio" name="status" value="solved" onclick="window.toggleThoughtStatus('solved')">
                        已解决
                    </label>
                </div>
            </div>
            <div id="additionalInput"></div>
            <div class="button-group">
                <button onclick="window.cancelThought()" class="cancel-thought-btn">取消</button>
                <button onclick="window.saveThought()" class="save-thought-btn">保存心得</button>
            </div>
        </div>
    `;
}

// 添加取消心得记录的函数
window.cancelThought = function() {
    // 直接清空第四区域
    document.querySelector('.card-4').innerHTML = '';
};

// 添加切换状态的函数
window.toggleThoughtStatus = function(status) {
    const additionalInput = document.getElementById('additionalInput');
    if (status === 'unsolved') {
        additionalInput.innerHTML = `
            <div class="form-group">
                <label>不通的路</label>
                <textarea id="thoughtDeadend" rows="4" placeholder="描述尝试过但不通的方案..."></textarea>
            </div>
        `;
    } else {
        additionalInput.innerHTML = `
            <div class="form-group">
                <label>成功方案</label>
                <textarea id="thoughtSolution" rows="4" placeholder="描述成功的解决方案..."></textarea>
            </div>
        `;
    }
}

// 保存心得的函数
window.saveThought = function() {
    try {
        const timestamp = document.getElementById('thoughtTimestamp').value;
        const problem = document.getElementById('thoughtProblem').value;
        
        // 检查是否选择了状态
        const statusRadio = document.querySelector('input[name="status"]:checked');
        if (!statusRadio) {
            throw new Error('请选择状态（已解决/未解决）');
        }
        const status = statusRadio.value;
        
        const solution = status === 'solved' ? document.getElementById('thoughtSolution').value : '';
        const deadend = status === 'unsolved' ? document.getElementById('thoughtDeadend').value : '';
        
        const thoughtData = {
            timestamp,
            problem,
            status,
            solution,
            deadend,
            step: window.currentProject.currentStep + 1
        };
        
        // 获取thoughts文件夹路径并确保它存在
        const thoughtsPath = path.join(path.dirname(path.dirname(window.currentProject.path)), 'thoughts');
        if (!fs.existsSync(thoughtsPath)) {
            fs.mkdirSync(thoughtsPath, { recursive: true });
        }
        
        // 使用项目名称作为文件名
        const sanitizedProjectName = window.currentProject.data.name.replace(/[<>:"/\\|?*]/g, '_');
        const filePath = path.join(thoughtsPath, `${sanitizedProjectName}.json`);
        
        // 读取现有文件或创建新的数组
        let thoughts = [];
        if (fs.existsSync(filePath)) {
            try {
                thoughts = JSON.parse(fs.readFileSync(filePath, 'utf8'));
                if (!Array.isArray(thoughts)) {
                    thoughts = [thoughts]; // 如果之前的文件不是数组格式，转换为数组
                }
            } catch (error) {
                console.error('Error reading existing thoughts file:', error);
                thoughts = []; // 如果读取失败，创建新数组
            }
        }
        
        // 添加新的心得
        thoughts.push(thoughtData);
        
        // 写入文件
        fs.writeFileSync(filePath, JSON.stringify(thoughts, null, 2), 'utf8');
        
        // 显示成功消息
        document.querySelector('.card-4').innerHTML = '<div class="success-message">心得已保存！</div>';
    } catch (error) {
        console.error('Error saving thought:', error);
        alert('保存心得失败: ' + error.message);
    }
}

// 添加保存过程的函数
window.saveProcess = function() {
    try {
        const steps = window.currentProject.data.steps;
        fs.writeFileSync(window.currentProject.path, JSON.stringify(window.currentProject.data, null, 2));
        alert('保存成功！');
        window.showProjectDetail(window.currentProject.path);
    } catch (error) {
        console.error('Error saving process:', error);
        alert('保存失败: ' + error.message);
    }
}

// 修改导出
module.exports = {
    updateThresholds,
    skillpointData,
    adjustThreshold
}; 

function createStepEditor(step, index) {
    return `
        <div class="step-editor" data-step="${index}">
            <h4>步骤 ${index + 1}</h4>
            <div class="step-inputs">
                <div class="materials-section">
                    <h5>材料</h5>
                    ${createMaterialsSelector(step, index)}
                </div>
                <div class="methods-section">
                    <h5>方法</h5>
                    ${createMethodsSelector(step, index)}
                </div>
                <div class="products-section">
                    <h5>产物</h5>
                    ${createProductsSelector(step, index)}
                </div>
            </div>
            <div class="step-description" id="step-description-${index}">
                ${generateStepDescription(step)}
            </div>
        </div>
    `;
}

// 修改材料选择处理函数
window.toggleMaterial = function(stepIndex, materialName) {
    const step = window.currentProject.data.steps[stepIndex];
    const checkbox = document.querySelector(`.step-editor[data-step="${stepIndex}"] input[data-material="${materialName}"]`);
    
    if (checkbox.checked) {
        step.materials = step.materials || [];
        step.materials.push({
            name: materialName,
            amount: 1,
            unit: window.currentMaterials.find(m => m.name === materialName)?.unit || ''
        });
    } else {
        step.materials = step.materials.filter(m => m.name !== materialName);
    }
    updateStepDescription(stepIndex);
}

// 修改方法选择处理函数
window.toggleMethod = function(stepIndex, methodName) {
    const step = window.currentProject.data.steps[stepIndex];
    const checkbox = document.querySelector(`.step-editor[data-step="${stepIndex}"] input[data-method="${methodName}"]`);
    
    if (checkbox.checked) {
        step.methods = step.methods || [];
        step.methods.push({ name: methodName });
    } else {
        step.methods = step.methods.filter(m => m.name !== methodName);
    }
    updateStepDescription(stepIndex);
}

// 修改产物选择处理函数
window.toggleProduct = function(stepIndex, productName) {
    const step = window.currentProject.data.steps[stepIndex];
    const checkbox = document.querySelector(`.step-editor[data-step="${stepIndex}"] input[data-product="${productName}"]`);
    
    if (checkbox.checked) {
        step.products = step.products || [];
        step.products.push({
            name: productName,
            amount: 1,
            unit: window.currentMaterials.find(m => m.name === productName)?.unit || ''
        });
    } else {
        step.products = step.products.filter(p => p.name !== productName);
    }
    updateStepDescription(stepIndex);
}

// 修改材料数量调整函数
window.adjustMaterialAmount = function(stepIndex, materialName, direction) {
    const step = window.currentProject.data.steps[stepIndex];
    const material = step.materials.find(m => m.name === materialName);
    if (material) {
        material.amount = direction === 'increase' ? material.amount + 1 : Math.max(1, material.amount - 1);
        updateStepDescription(stepIndex);
    }
}

// 修改产物数量调整函数
window.adjustProductAmount = function(stepIndex, productName, direction) {
    const step = window.currentProject.data.steps[stepIndex];
    const product = step.products.find(p => p.name === productName);
    if (product) {
        product.amount = direction === 'increase' ? product.amount + 1 : Math.max(1, product.amount - 1);
        updateStepDescription(stepIndex);
    }
}

// 修改隐藏功能为移除功能
window.hideThreshold = function(type, varName) {
    const element = document.querySelector(`[data-varname="${varName}"]`);
    if (element) {
        // 从DOM中移除元素
        element.remove();

        // 从数据中移除
        if (type === 'change') {
            // 从能力点调整中移除
            window.currentAbilities = window.currentAbilities.filter(ability => 
                ability.varName !== varName
            );
        } else if (type === 'ability') {
            // 从能力点门槛中移除
            currentThresholds.abilities = currentThresholds.abilities.filter(ability => 
                ability.varName !== varName
            );
        } else if (type === 'material') {
            // 从原材料门槛中移除
            currentThresholds.materials = currentThresholds.materials.filter(material => 
                material.varName !== varName
            );
        }
    }
};

// 修改取消确认函数
window.confirmCancel = function() {
    if (confirm('确定要取消执行吗？已执行的进度将不会保存。')) {
        // 自动清空第四区域（取消未保存的心得）
        document.querySelector('.card-4').innerHTML = '';
        
        // 停止计时器
        if (executionState.timer) {
            clearInterval(executionState.timer);
        }
        // 返回到项目详情页面
        showProjectDetail(window.currentProject.path);
    }
};

// 添加更新能力点和材料的函数
async function updateSkillpointAndMaterials(projectPath, content) {
    try {
        const skillpointPath = path.join(path.dirname(path.dirname(projectPath)), 'skillpoint.json');
        let skillpointData = { attributes: [] };
        
        // 读取现有的 skillpoint.json
        if (fs.existsSync(skillpointPath)) {
            skillpointData = JSON.parse(fs.readFileSync(skillpointPath, 'utf8'));
        }

        // 计算材料总消耗和总产出
        const materialConsumption = {};
        const materialProduction = {};
        
        content.steps.forEach(step => {
            // 统计消耗材料
            step.materials?.forEach(material => {
                materialConsumption[material.varName] = (materialConsumption[material.varName] || 0) + 
                    parseInt(material.amount || 0);
            });
            
            // 统计产出材料
            step.products?.forEach(product => {
                materialProduction[product.varName] = (materialProduction[product.varName] || 0) + 
                    parseInt(product.amount || 0);
            });
        });

        // 更新能力点
        if (content.thresholds?.abilityChanges) {
            content.thresholds.abilityChanges.forEach(change => {
                const ability = skillpointData.attributes.find(attr => attr.varName === change.varName);
                if (ability) {
                    ability.currentValue = Math.min(
                        ability.max,
                        Math.max(
                            ability.min,
                            (parseInt(ability.currentValue) || ability.defaultValue) + parseInt(change.change)
                        )
                    );
                }
            });
        }

        // 更新材料消耗和产出
        Object.entries(materialConsumption).forEach(([varName, amount]) => {
            const material = skillpointData.attributes.find(attr => attr.varName === varName);
            if (material) {
                material.currentValue = (parseInt(material.currentValue) || material.defaultValue) - amount;
            }
        });

        Object.entries(materialProduction).forEach(([varName, amount]) => {
            const material = skillpointData.attributes.find(attr => attr.varName === varName);
            if (material) {
                material.currentValue = (parseInt(material.currentValue) || material.defaultValue) + amount;
            }
        });

        // 保存更新后的 skillpoint.json
        fs.writeFileSync(skillpointPath, JSON.stringify(skillpointData, null, 2), 'utf8');

        return {
            abilityChanges: content.thresholds?.abilityChanges || [],
            materialConsumption,
            materialProduction
        };
    } catch (error) {
        console.error('Error updating skillpoint and materials:', error);
        throw error;
    }
}

// 修改 saveProject 函数
async function saveProject(projectPath, content) {
    try {
        // 如果有执行记录，计算每个步骤的平均用时
        if (content.executions && content.executions.length > 0) {
            content.steps = content.steps.map((step, index) => {
                const totalStepTime = content.executions.reduce((sum, exec) => 
                    sum + (exec.actualTimes[index] || 0), 0);
                const avgStepTime = totalStepTime / content.executions.length;
                return {
                    ...step,
                    averageTime: avgStepTime
                };
            });

            // 计算项目的平均总用时
            content.averageTotalTime = content.executions.reduce((sum, exec) => 
                sum + exec.totalActualTime, 0) / content.executions.length;
        }

        // 保存项目文件
        fs.writeFileSync(projectPath, JSON.stringify(content, null, 2), 'utf8');
        
        // 更新能力点和材料
        const updates = await updateSkillpointAndMaterials(projectPath, content);
        
        // 显示更新提示
        showUpdateNotification(updates);
    } catch (error) {
        console.error('Error saving project:', error);
        throw error;
    }
}

// 添加更新提示函数
function showUpdateNotification(updates) {
    const card4 = document.querySelector('.card-4');
    let notification = '<div class="update-notification">';
    
    // 显示能力点变化
    if (updates.abilityChanges.length > 0) {
        notification += '<h3>能力点变化：</h3>';
        updates.abilityChanges.forEach(ability => {
            notification += `<p>${ability.name} ${ability.change > 0 ? '+' : ''}${ability.change}</p>`;
        });
    }
    
    // 显示材料消耗
    if (Object.keys(updates.materialConsumption).length > 0) {
        notification += '<h3>材料消耗：</h3>';
        Object.entries(updates.materialConsumption).forEach(([varName, amount]) => {
            // 从 skillpointData 中查找对应的材料名称
            const material = window.skillpointData.attributes.find(attr => attr.varName === varName);
            const materialName = material ? material.name : varName;
            notification += `<p>${materialName} -${amount}</p>`;
        });
    }
    
    // 显示材料产出
    if (Object.keys(updates.materialProduction).length > 0) {
        notification += '<h3>材料产出：</h3>';
        Object.entries(updates.materialProduction).forEach(([varName, amount]) => {
            // 从 skillpointData 中查找对应的材料名称
            const material = window.skillpointData.attributes.find(attr => attr.varName === varName);
            const materialName = material ? material.name : varName;
            notification += `<p>${materialName} +${amount}</p>`;
        });
    }
    
    notification += '</div>';
    card4.innerHTML = notification;
} 